package br.com.virtual.cadastrar.service.impl;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;

import br.com.virtual.base.uteis.DirectoryManager;
import br.com.virtual.base.uteis.VirtualConstants;
import br.com.virtual.cadastrar.model.Foto;
import br.com.virtual.cadastrar.service.FotoService;
import br.com.virtual.cadastrar.service.PhotoManagerService;

@Stateless
@Local(PhotoManagerService.class)
public class PhotoManagerServiceImpl implements PhotoManagerService,
		VirtualConstants {

	@EJB
	FotoService fotoService;
	Logger logger = Logger.getLogger(this.getClass().toString());
	FileHandler fh;

	@PostConstruct
	private void init() {

		try {
			fh = new FileHandler("log-teste.txt");
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		logger.addHandler(fh);
	}

	@Override
	public List<Foto> fotosToWrite() {

		List<Long> ids = this.getIds(DirectoryManager.listFilesDirectory());
		// String idsClauseNotIn = this.getIdsAsString(ids);

		// if (idsClauseNotIn.isEmpty())
		if (ids == null || ids.isEmpty())
			return fotoService.getList();
		else
			return fotoService.getListNotIn(ids);
	}

	@Override
	public void addPhotosToTemporaryDirectory(List<Foto> fotos) {

		int count = 0;
		String temp = DirectoryManager.getDiretorioTemporario()
				.getAbsolutePath();

		for (Foto f : fotos) {
			count++;
			if (f.getDescricao() == null || f.getDescricao().isEmpty())
				f.setDescricao(String.valueOf(f.getId()));
			String nomeArquivo = f.getDescricao().toString() + ".jpg";
			String arquivo = temp + "\\" + nomeArquivo;
			this.createFile(f.getImagem(), arquivo);
		}

		logger.warning("TOTAL DE IMAGENS CRIADAS ====>>>>" + count);

	}

	// public String getRealPath() {
	//
	// return DirectoryManager.getRealPath();
	// }

	@Override
	public void createFile(byte[] image, String filePath) {

		FileOutputStream fos;

		try {

			fos = new FileOutputStream(filePath);
			fos.write(image);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();

			logger.warning("FileNotFoundException... |" + filePath + "|");

		} catch (IOException e) {

			logger.warning("IOException... |" + filePath + "|");
		}
	}

	/*
	 * Métodos auxiliares
	 */
	private List<Long> getIds(List<String> fileNames) {

		List<Long> ids = new ArrayList<Long>();

		for (String nome : fileNames) {

			String[] arquivo = nome.split("\\.");
			if (arquivo.length == 2 && arquivo[1].equals("jpg")) {

				try {
					Long id;
					if ((arquivo[0]).contains("fic")) {
						arquivo[0].split("\\_");
						id = new Long(arquivo[1]);
					} else
						id = new Long(arquivo[0]);
					ids.add(id);
				} catch (NumberFormatException e) {
				}
			}
		}

		return ids;
	}

}
